package com.sxbbc.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.api.common.BaseMapping;
import com.sxbbc.api.service.IBaseService;
import com.sxbbc.common.basics.files.RestUploadFileInfo;
import com.sxbbc.common.basics.files.UploadUtils;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.date.DateUtil;
import com.sxbbc.common.basics.utils.encrypts.des.DESEncode;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.basics.wx.util.WxSign;
import com.sxbbc.common.core.dto.jz.SearchVo;
import com.sxbbc.common.core.entity.jz.Address;
import com.sxbbc.common.core.entity.jz.AppVersion;
import com.sxbbc.common.core.entity.jz.CCustomer;
import com.sxbbc.common.core.entity.jz.InfoWx;
import com.sxbbc.common.core.entity.jz.ProcMain;
import com.sxbbc.common.core.entity.jz.SiteKey;
import com.sxbbc.common.core.enums.BusinessTypeEnums;
import com.sxbbc.common.core.enums.SolrSortEnums;
import com.sxbbc.common.core.service.IAddressService;
import com.sxbbc.common.core.service.IAppVersionService;
import com.sxbbc.common.core.service.ICCustomerService;
import com.sxbbc.common.core.service.IProcMainService;
import com.sxbbc.common.core.service.ISiteKeyService;
import com.sxbbc.common.core.service.system.login.LoginTokenService;
import com.sxbbc.common.core.utils.BasePage;
import com.sxbbc.common.core.utils.FileUtils;
import com.sxbbc.common.core.utils.MultipartFileToFile;
import com.sxbbc.common.core.utils.RedisUtils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

/**
 * 常用集合
 *
 * @author leehao
 * @date 2019-05-15 15:30
 */
@RestController

public class BaseController {

    @Autowired
    private IBaseService baseService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private LoginTokenService loginTokenService;
    @Autowired
    private ISiteKeyService siteKeyService;
    @Autowired
    private IProcMainService procMainService;
    @Autowired
    private IAppVersionService appVersionService;
    @Autowired
    private ICCustomerService customerService;

    /**
     * 猜你喜欢
     *
     * @param token 获取cid
     * @param page  分页
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = BaseMapping.QUERY_GUESS_LIKE)
    public RestResponse guessLike(String token, BasePage<ProcMain> page) {
        Integer cid = null;
        IPage<ProcMain> list = new Page<ProcMain>();
        if (StringUtils.isNotBlank(token)) {
            cid = loginTokenService.validLoginCid(token);
            list = baseService.queryLikeList(cid, page);
            if (CollectionUtils.isEmpty(list.getRecords()) || list.getRecords().size() < 9) {
                list = procMainService.queryDefaultProductList(page);
            }
        } else {
            list = procMainService.queryDefaultProductList(page);
        }
        for (ProcMain p : list.getRecords()) {
            if (CalcuUtils.getInstance().isEquals(p.getBType(), BusinessTypeEnums.OWN_BUSINESS.getId())) {
                p.setBTypeName(BusinessTypeEnums.OWN_BUSINESS.getName());
            }
            p.setActivitySign("");
        }
        return GetRest.getSuccess("success", list);
    }

    /**
     * 图片统一上传
     *
     * @param file 图片文件
     * @return 上传成功返回图片url
     * @author leehao
     */
    @RequestMapping(value = BaseMapping.UPLOAD_FILE)
    public RestResponse handleUploadFile(@RequestParam(required = false) MultipartFile file, String ext) {
        String url = "";
        //TODO 原來寫法是RestUploadFileInfo result = UploadUtils.getInstance().uploadFilefastdfs(file,ext);
//        RestUploadFileInfo result = UploadUtils.getInstance().uploadFileQN(file);
////        /*RestUploadFileInfo result = UploadUtils.getInstance().uploadFile(file);*/
//        if (result.isStatus()) {
//            url = result.getData();
//        } else {
//            return GetRest.getFail("图片上传失败：" + result.getDesc());
//        }
        try {
            File fe= MultipartFileToFile.multipartFileToFile(file);
             url= FileUtils.up(fe);
        }catch (Exception e){
            return GetRest.getFail("上传图片失败");
        }
        return GetRest.getSuccess("success", url);
    }

    /**
     * 搜索功能
     *
     * @param search 搜索vo对象
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = BaseMapping.SEARCH)
    public RestResponse handleSearch(SearchVo search, Integer cpage, Integer csize) {
        //排序类型为空时则默认排序
        if (search.getSortType() == null) {
            search.setSortType(SolrSortEnums.NORMAL.getId());
        }
        //页码为空默认第一页
        if (cpage == null) {
            cpage = 1;
        }
        CalcuUtils calUtil = CalcuUtils.getInstance();
        //只对价格设置升序降序
        if (!calUtil.isEquals(search.getSortType(), SolrSortEnums.PRICE.getId())) {
            search.setSortDesc("asc");
        }
        if (calUtil.isEquals(search.getSortType(), SolrSortEnums.SALE_NUMS.getId())) {
            search.setSortDesc("desc");
        }
        Map<String, Object> map = baseService.handleSearchProductOrBusiness(search, cpage, csize);
        return GetRest.getSuccess("success", map);
    }

    /**
     * 搜索 大家都在搜
     *
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @GetMapping(value = BaseMapping.QUERY_SITE_KEY)
    public RestResponse querySiteKey() {
        QueryWrapper<SiteKey> wrapper = new QueryWrapper<>();
        wrapper.eq("status", StaticUtils.STATUS_YES);
        wrapper.orderByDesc("sort");
        List<SiteKey> list = siteKeyService.list(wrapper);
        return GetRest.getSuccess("success", list);
    }

    /**
     * 地址列表
     *
     * @param address 地址对象，关键字段见下
     *                pid 父id
     *                level 层级
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @GetMapping(value = BaseMapping.ADDRESS)
    public RestResponse address(Address address) {
        List<Address> addressList = addressService.queryAddressByParentId(address);
        return GetRest.getSuccess("success", addressList);
    }

    /**
     * 清除缓存
     *
     * @author leehao
     */
    @RequestMapping(value = BaseMapping.REFRESH_CACHE)
    public RestResponse refreshCache() {
        try {
            baseService.refreshCache();
        } catch (Exception e) {
            return GetRest.getFail("清除缓存失败");
        }
        return GetRest.getSuccess("清除成功");
    }

    /**
     * 获取最新版本号信息
     *
     * @author leehao
     */
    @RequestMapping(value = BaseMapping.GET_APP_VERSION)
    public RestResponse getAppVersion() {
        AppVersion appVersion = appVersionService.getOne(new QueryWrapper<AppVersion>());
        if (appVersion == null) {
            return GetRest.getFail("未获取到最新版本号信息");
        }
        return GetRest.getSuccess("", appVersion);
    }

    /**
     * jsapi_ticket签名
     *
     * @return
     * @author xiaoky
     */
    @RequestMapping(value = BaseMapping.GET_WX_JSAPI_TICKET)
    public RestResponse getWxJsapiTicket(String url) {
        url = URLDecoder.decode(url);
        String jsApiTicket = RedisUtils.getInstance().getWxJsApiTicket();
        InfoWx info = RedisUtils.getInstance().getWxInfo();
        Map<String, String> map = WxSign.sign(jsApiTicket, url);
        map.put("appId", info.getAppId());
        return GetRest.getSuccess("", map);
    }

    /**
     * 解密字符串
     *
     * @param msg
     * @return
     * @author xiaoky
     */
    @RequestMapping(value = BaseMapping.DECRYPT_MSG)
    public RestResponse decryptMsg(String msg) {
        String decrypt = DESEncode.getInstance().decrypt(msg);
        return GetRest.getSuccess("", decrypt);
    }

    /**
     * 获取分享数据
     *
     * @param token 获取cid
     * @param type  区分商品、商家、分享码
     * @return
     * @author xiaoky
     */
    @RequestMapping(value = BaseMapping.GET_SHARE_MSG)
    public RestResponse getShareMsg(String token, Integer type, String data) {
        Integer cid = null;
        if (!StringUtils.isBlank(token)) {
            cid = loginTokenService.validLoginCid(token);
        }
        if (!StringUtils.isBlank(token) && cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        Map<String, Object> map = baseService.getShareMsg(cid, type, data);
        return GetRest.getSuccess("", map);
    }

    /**
     * 校验绑定关系
     *
     * @param token      获取cid
     * @param inviteCode 推荐人邀请码
     * @return
     * @author xiaoky
     */
    @RequestMapping(value = BaseMapping.SHARE_CHECK)
    public RestResponse shareCheck(String token, String inviteCode) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        CCustomer customer = customerService.getById(cid);
        if (customer == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        CCustomer queryCustomer = new CCustomer();
        queryCustomer.setInviteCode(inviteCode);
        CCustomer refereeCustomer = customerService.getCustomer(queryCustomer);
        if (refereeCustomer == null) {
            return GetRest.getFail("您已经绑定过其它用户,请关注公众号");
        }
        if (CalcuUtils.getInstance().isEquals(customer.getParentid(), refereeCustomer.getId())) {
            return GetRest.getSuccess("该用户已是您的推荐人");
        }

        return GetRest.getFail("您已经绑定过其它用户,请关注公众号");
    }

    @GetMapping(value = BaseMapping.GET_SERVER_TIME)
    public RestResponse getServerTime() {
        long currentTime = DateUtil.getInstance().currentTimeMillis();
        return GetRest.getSuccess("", currentTime);
    }

    /**
     * 是否过滤敏感内容，IOS上架用，开启后前端不显示
     * 1 开启，即IOS审核中
     * 0 关闭，即IOS审核通过
     *
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = BaseMapping.GET_CAN_FILTER)
    public Integer canFilter() {
        AppVersion appVersion = appVersionService.getOne(new QueryWrapper<>());
        if (appVersion == null) {
            return 0;
        }
        return appVersion.getIosVersion();
    }
}
